package com.hd.trans.widgets.views.floatwindow.apply

import android.animation.ValueAnimator
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.os.Build
import android.text.TextUtils
import android.view.View
import android.view.View.OnClickListener
import android.view.WindowManager
import com.hd.trans.R
import com.hd.trans.binding.visible
import com.hd.trans.databinding.SimultaneousFloatWindowBinding
import com.hd.trans.utils.ScreenUtil
import com.hd.trans.utils.SingleClickGestureDetector
import com.hd.trans.widgets.views.floatwindow.base.BaseFloatWindow
import com.hd.trans.widgets.views.floatwindow.component.FloatWindow
import com.hd.trans.widgets.views.floatwindow.component.ShowType

class SimultaneousFloatWindow(
    private val context: Context,
    private val packageName: String? = null,
    private val onFloatClickListener: OnFloatClickListener? = null,
): BaseFloatWindow<SimultaneousFloatWindowBinding>(context), OnClickListener {
    private lateinit var animatorLoading: AnimationDrawable
    private var mHideHeaderAnim:ValueAnimator? = null
    private var mShowHeaderAnim:ValueAnimator? = null
    private var showType = ShowType.Bilingual
    override fun getLayoutId(): Int {
        return R.layout.simultaneous_float_window
    }

    private val rawHeight by lazy {
        mDataBinding.layoutTop.measuredHeight
    }

    override fun createFloatWindow(context: Context): FloatWindow {
        ScreenUtil.init(contentView.context)
        return FloatWindow.With(mContext, contentView)
            .setWidth(WindowManager.LayoutParams.MATCH_PARENT)
            .setAutoAlign(false) //是否自动贴边
            .setModality(false) //是否模态窗口
            .setMoveAble(true) // 是否可拖动
            .setDeskTopWindow(true) // 是否在桌面显示
            .setStartLocation(0, ScreenUtil.getScreenHeight() - contentView.height) //初始位置
            .create()
    }

    @SuppressLint("ClickableViewAccessibility")
    override fun initView(dataBinding: SimultaneousFloatWindowBinding) {
        mDataBinding.apply {
            click = this@SimultaneousFloatWindow
            animatorLoading = layoutLoading.background as AnimationDrawable
            animatorLoading.start()
            val onRvClick = SingleClickGestureDetector {
                onSingleClick()
            }
            //禁止滑动
            scrollViewOriginal.setOnTouchListener { _, event ->
                onRvClick.onTouchEvent(event)
                true
            }
            scrollViewTrans.setOnTouchListener { _, event ->
                onRvClick.onTouchEvent(event)
                true
            }
            //固定布局高度
            layoutMain.post {
                layoutMain.layoutParams.height = layoutMain.measuredHeight
            }
            updateShowType(showType)
        }
    }

    private fun onSingleClick() {
        if (mDataBinding.layoutTop.measuredHeight > 0){
            mHideHeaderRunnable.run()
        }
        else {
            mShowHeaderRunnable.run()
        }
    }

    private val mHideHeaderRunnable by lazy {
        Runnable {
            mHideHeaderAnim?.cancel()
            mHideHeaderAnim = ValueAnimator.ofInt(rawHeight,0).setDuration(300).apply {
                addUpdateListener {
                    val value = it.animatedValue as Int
                    mDataBinding.layoutTop.layoutParams.height = value
                    mDataBinding.layoutTop.requestLayout()
                }
                start()
            }
        }
    }

    private val mShowHeaderRunnable by lazy {
        Runnable {
            postHideHeaderView()
            mShowHeaderAnim?.cancel()
            mShowHeaderAnim = ValueAnimator.ofInt(0, rawHeight).setDuration(300).apply {
                addUpdateListener {
                    val value = it.animatedValue as Int
                    mDataBinding.layoutTop.layoutParams.height = value
                    mDataBinding.layoutTop.requestLayout()
                }
                start()
            }

        }
    }

    private fun postHideHeaderView(){
        if (!isShowing)
            return

        //2.5秒后自动隐藏顶部操作栏
        mHideHeaderAnim?.cancel()
        mDataBinding.layoutTop.removeCallbacks(mHideHeaderRunnable)
        mDataBinding.layoutTop.postDelayed(mHideHeaderRunnable,2500)
    }

    private fun updateShowType(showType: ShowType) {
        mDataBinding.btnChangeShowType.text = showType.typeName
        when (showType){
            ShowType.Bilingual -> {
                mDataBinding.scrollViewOriginal.visible = true
                mDataBinding.scrollViewTrans.visible = true
            }
            ShowType.Original -> {
                mDataBinding.scrollViewOriginal.visible = true
                mDataBinding.scrollViewTrans.visible = false
            }
            ShowType.Translation -> {
                mDataBinding.scrollViewOriginal.visible = false
                mDataBinding.scrollViewTrans.visible = true
            }
        }
    }

    fun changeLang(fromLang: String, toLang: String){
        mDataBinding.tvFromLang.text = fromLang
        mDataBinding.tvToLang.text = toLang
    }

    fun changeContent(originalContent: String, transContent: String){
        if(originalContent.length > 150){
            changeOriginalContent(originalContent.substring(originalContent.length - 150))
        }else{
            changeOriginalContent(originalContent)
        }
        if(transContent.length > 150){
            changeTransContent(transContent.substring(transContent.length - 150))
        }else{
            changeTransContent(transContent)
        }
    }

    private fun changeOriginalContent(content: String){
        if (!isShowing)
            return
        mDataBinding.layoutLoading.visible = TextUtils.isEmpty(content)
        if(mDataBinding.layoutLoading.visible){
            animatorLoading.start()
        }else{
            animatorLoading.stop()
        }
        mDataBinding.tvOriginal.text = content
        mDataBinding.scrollViewOriginal.fullScroll(View.FOCUS_DOWN)
    }

    private fun changeTransContent(content: String){
        if (!isShowing)
            return
        mDataBinding.progressbar.visible = TextUtils.isEmpty(content) && !TextUtils.isEmpty(mDataBinding.tvOriginal.text)
        mDataBinding.tvTrans.text = content
        mDataBinding.scrollViewTrans.fullScroll(View.FOCUS_DOWN)
    }

    override fun onClick(v: View?) {
        postHideHeaderView()
        when(v){
            mDataBinding.btnChangeShowType -> {
                showType = when (showType){
                    ShowType.Bilingual -> ShowType.Original
                    ShowType.Original -> ShowType.Translation
                    ShowType.Translation -> ShowType.Bilingual
                }
                updateShowType(showType)
                onFloatClickListener?.showType(v, showType)
            }
            mDataBinding.btnSet -> {
                onFloatClickListener?.setting(v)
            }
            mDataBinding.btnScreenRecover -> {
                hidden()
                backToApp(context)
                onFloatClickListener?.screenRecover(v)
            }
            mDataBinding.btnCloseFloatWindow -> {
                hidden()
                backToApp(context)
                onFloatClickListener?.closeFloatWindow(v)
            }
            mDataBinding.layoutContent -> {
                onSingleClick()
            }
        }
    }

    private fun toDesktop(context: Context){
        val desktop = Intent(Intent.ACTION_MAIN)
        desktop.addCategory(Intent.CATEGORY_HOME)
        //desktop.flags = Intent.FLAG_ACTIVITY_SINGLE_TOP
        context.startActivity(desktop)
    }

    private fun backToApp(context: Context){
        packageName?.let {name ->
            context.packageManager.getLaunchIntentForPackage(name)?.let {intent ->
                context.startActivity(intent)
            }
        }
    }

    override fun show() {
        toDesktop(context)
        changeContent("","")
        mDataBinding.layoutTop.post {
            mShowHeaderRunnable.run()
        }
        super.show()
    }
}